﻿using FictionsDownload.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace FictionsDownload.BLL
{
    class BackupAPI
    {
        string Message { get; set; }
        string ServerUrl { get; set; }
        public BackupAPI()
        {
            ServerUrl = "http://localhost:64476/api/";
        }
        public BackupAPI(string url)
        {
            ServerUrl = url;
        }
        #region Get
        private WebClient BaseClient()
        {
            WebClient client = new WebClient();
            client.Headers["Type"] = "GET";
            client.Headers["Accept"] = "application/json";
            client.Encoding = Encoding.UTF8;
            return client;
        }

        public Dictionary<string, DateTime> Get<T>(string serverURL)
        {
            WebClient client = BaseClient();
            string obj = client.DownloadString(new Uri(ServerUrl + serverURL));
            JObject jo = (JObject)JsonConvert.DeserializeObject(obj);
            Message = jo["msg"].ToString();
            if (jo["state"].ToString() == "false")
            {
                return null;
            }
            return jo["data"].ToDictionary(d=> ((JProperty)d).Name,d=> DateTime.Parse(((JProperty)d).Value.ToString()));
        }

        public T Get<T>(string serverURL,string UUID)
        {
            WebClient client = BaseClient();
            string obj = client.DownloadString(new Uri(ServerUrl + serverURL + "?UUID=" + UUID));
            JObject jo = (JObject)JsonConvert.DeserializeObject(obj);
            Message = jo["msg"].ToString();
            if (jo["state"].ToString() == "false")
            {
                return default(T);
            }
            return jo["data"].ToObject<T>();
        }
        public Dictionary<string, DateTime> Get<T>(string serverURL,int FolderId)
        {
            WebClient client = BaseClient();
            string obj = client.DownloadString(new Uri(ServerUrl + serverURL + "?FolderId=" + FolderId));
            JObject jo = (JObject)JsonConvert.DeserializeObject(obj);
            Message = jo["msg"].ToString();
            if (jo["state"].ToString() == "false")
            {
                return null;
            }
            return jo["data"].ToDictionary(d => ((JProperty)d).Name, d => DateTime.Parse(((JProperty)d).Value.ToString()));
        }
        #endregion
        #region Put
        public async Task<object> Put<T>(string serverURL, T item)
        {
            //创建一个处理序列化的DataContractJsonSerializer
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            //将资料写入MemoryStream
            serializer.WriteObject(ms, item);
            //一定要在这设定Position
            ms.Position = 0;
            HttpContent content = new StreamContent(ms);//将MemoryStream转成HttpContent
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            HttpClient client = new HttpClient();
            //由HttpClient发出Put Method
            HttpResponseMessage response = await client.PutAsync(ServerUrl + serverURL, content);
            if (!response.IsSuccessStatusCode)
            {
                return null;
            }
            //响应成功，获取响应的数据
            string result = response.Content.ReadAsStringAsync().Result;
            JObject jo = (JObject)JsonConvert.DeserializeObject(result);
            Message = jo["msg"].ToString();
            if (jo["state"].ToString() == "false")
            {
                return default(T);
            }
            return jo["data"].ToObject<T>();
        }
        #endregion
    }
}
